package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MemberMapper memberMapper;

    /**
     * 手机验证码登录
     * @param validateCode
     * @param telephone
     * @return
     */
    @Override
    public boolean login(String validateCode, String telephone) {
        //校验验证码是否正确
        boolean flag = validateCode(validateCode, telephone);
        if(flag){
            //判断会员表内是否已经注册了，如果没有就注册
            Member member = memberMapper.selectByPhone(telephone);
            if(member == null){
                memberMapper.add(telephone);
            }
            return flag;
        }
        return false;
    }
    /**
     * 验证验证码和电话号码
     * @param code 用户输入的验证码
     * @param phoneNumber 用户输入的电话号码
     * @return 验证结果
     */
    public boolean validateCode(String code, String phoneNumber) {
        String storedPhoneNumber = (String) redisTemplate.opsForValue().get(code);
        if (storedPhoneNumber == null) {
            return false;
        }
        return storedPhoneNumber.equals(phoneNumber);
    }
}
